namespace Hont
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.Networking;
    using System.Runtime.CompilerServices;

    public class UnityWebRequestWrap : INotifyCompletion
    {
        private WebAsync mWebAsync;
        private WebAsyncRequestContext mRequestContext;
        private WebAsyncResponseContext mResponseContext;
        private Action mOnCompleted;
        private UnityWebRequest mRequest;

        public bool IsCompleted => false;


        public UnityWebRequestWrap(WebAsync webAsync, WebAsyncRequestContext requestContext, UnityWebRequest request)
        {
            mWebAsync = webAsync;
            mRequestContext = requestContext;
            mRequest = request;
        }

        public WebAsyncResponseContext GetResult()
        {
            return mResponseContext;
        }
        
        public UnityWebRequestWrap GetAwaiter()
        {
            return this;
        }

        private IEnumerator WaitWebRequest()
        {
            mRequest.timeout = mRequestContext.TimeOut;
            yield return mRequest.SendWebRequest();
            mResponseContext.Result = mRequest.result;
            mResponseContext.WebRequest = mRequest;

            mOnCompleted();
        }

        #region INotifyCompletion

        void INotifyCompletion.OnCompleted(Action continuation)
        {
            mOnCompleted = continuation;

            mWebAsync.StartCoroutine(WaitWebRequest());
        }

        #endregion
    }
}